package com.xpec.c4.game.cronjob;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;

import org.quartz.CronExpression;

import redis.clients.jedis.Jedis;

import com.ms.service.db.jedis.JedisManager;
import com.xpec.c4.game.time.TimeSys;
import com.xpec.c4.service.module.ModuleName;

public class CronJobDAO {

	private static String moduleName = ModuleName.GAMELOBBY;
	
	private static int scheduleCount = 3;
	
	/**
	 * 開機add cron Timer時 檢查排程 
	 * 如果是null 就是完全沒執行過 
	 * 如果不是 就要檢查redis上的時間點 
	 * 如果還沒做得要補做 
	 * 做完要刪除
	 */
	public static ArrayList<Long> determinedSchedule(CronTaskTimer taskTimer){
		CronExpression ce = null;
		try {
			 ce = new CronExpression(taskTimer.getCronExpressions());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		Jedis jedis = JedisManager.getResource(moduleName);
		String key = taskTimer.getClass().getSimpleName();
		HashSet<String> scheduleSet = (HashSet<String>) jedis.smembers(key);
		ArrayList<Long> notDoneList = null;
		if(scheduleSet.size() <= 0){
			//第一次使用這個map沒有紀錄
			//要幫他新增 
			long time = TimeSys.currentTimeMills();
			for (int count = 0; count < scheduleCount; count++) {
				time = getNextScheduleTime(ce, new Date(time));
				jedis.sadd(key, String.valueOf(time));
			}
			
			
		}else{
			notDoneList = new ArrayList<Long>();
			//檢查是否有沒做過的
			for (String schedule : scheduleSet) {
				long time = Long.valueOf(schedule);
				if(TimeSys.currentTimeMills() > time){
					notDoneList.add(time);
				}
			}
		}
		JedisManager.returnResource(moduleName, jedis);
		return notDoneList;
	}
	
	/**
	 * 建立新的排程
	 * @param taskTimer
	 * @param cronExpression
	 */
	public static void createNewSchedule(CronTaskTimer taskTimer){
		CronExpression ce = null;
		try {
			 ce = new CronExpression(taskTimer.getCronExpressions());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Jedis jedis = JedisManager.getResource(moduleName);
		String key = taskTimer.getClass().getSimpleName();
		jedis.del(key);
		long time = TimeSys.currentTimeMills();
		
		for (int count = 0; count < scheduleCount; count++) {
			time = getNextScheduleTime(ce, new Date(time));
			jedis.sadd(key, String.valueOf(time));
		}

		JedisManager.returnResource(moduleName, jedis);
	}
		
	private static long getNextScheduleTime(CronExpression ce , Date nowDate){
		return ce.getNextValidTimeAfter(nowDate).getTime();
	}

	public static void main(String[] args) {
		System.out.println(CronJobDAO.class.getSimpleName());
	}
}
